<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useMainLogin } from '@/store/user'
import { useMainStore } from '@/store/index'
import POISearch from '@components/POISearch/index.vue'
import { resetPwd,smsResetPwd } from '@/api/user'
import * as mars3d from "mars3d"

// 声明全局类型
declare global {
  interface Window {
    map: any;
  }
}

const user = useMainLogin()
const Cesium = mars3d.Cesium
const store = useMainStore()
const xgFlag = ref<boolean>(true)
const dialogTableVisible = ref<boolean>(false)
const mapChecked = ref<number>(0)
const form = ref({oldPassword:'',password: '',smsCode:''})
const rules = ref({
  oldPassword: [{ required: true, trigger: 'blur', message: "密码格式不正确,请输入6位及以上作为密码", pattern:/^[0-9A-Za-z]{6,}$/ }],
  password: [{ required: true, trigger: 'blur', message: "密码格式不正确,请输入6位及以上作为密码", pattern:/^[0-9A-Za-z]{6,}$/ }],
})


const platType = ref<string>('0')
const reSetPassWard = ref<FormInstance>()

const checked1 = ref(true)
const checked2 = ref(true)
const checked3 = ref(true)
const checked4 = ref(true)
const baseurl = import.meta.env.VITE_APP_BASE_WmsUrl
const name = import.meta.env.VITE_APP_BASE_WmsName

onMounted(() => {
  document.addEventListener('fullscreenchange', () => {
    if (!document.fullscreenElement) {
      // 当用户通过其他方式（如按ESC）退出全屏时，也需要还原状态
      const marsContainer = document.querySelector('.mars3d-container') as HTMLElement
      const roadInfoBox = document.querySelector('.roadInfoBox') as HTMLElement
      const polyMainInfoBox = document.querySelector('.polyMainInfoBox') as HTMLElement
      
      if (marsContainer) {
        marsContainer.style.width = ''
        marsContainer.style.height = ''
      }
      if (roadInfoBox) roadInfoBox.style.display = ''
      if (polyMainInfoBox) polyMainInfoBox.style.display = ''
    }
  })

  showMap()
  // addWmslayer(baseurl,`road_defect_inspection${name}:公里桩WGS84${name}`,'glz')
  // addWmslayer(baseurl,`road_defect_inspection${name}:百米桩WGS84${name}`,'bmz')

  addGeoJson('http://139.9.173.189:8080/geoserver/road_defect_inspection_prod/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=road_defect_inspection_prod%3A%E5%85%AC%E9%87%8C%E6%A1%A9WGS84_prod&maxFeatures=50&outputFormat=application%2Fjson','glz')
  addGeoJson('http://139.9.173.189:8080/geoserver/road_defect_inspection_prod/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=road_defect_inspection_prod%3A%E7%99%BE%E7%B1%B3%E6%A1%A9WGS84_prod&maxFeatures=50&outputFormat=application%2Fjson','bmz')

})

const flyTo = () => {
  if (user.position.length > 2) {
    let extent = {
      xmin: user.position[0],
      xmax: user.position[1],
      ymin: user.position[2],
      ymax: user.position[3],
    }
    window.map.flyToExtent(extent)
  } else {
    window.map.flyToPoint(user.position,{
      radius: user.height,
    })
  }
}

const preview = () => {
  const marsContainer = document.querySelector('.mars3d-container') as HTMLElement
  const roadInfoBox = document.querySelector('.roadInfoBox') as HTMLElement
  const polyMainInfoBox = document.querySelector('.polyMainInfoBox') as HTMLElement
  
  if (marsContainer) {
    if (document.fullscreenElement) {
      // 退出全屏
      document.exitFullscreen()
      if (roadInfoBox) roadInfoBox.style.display = ''
      if (polyMainInfoBox) polyMainInfoBox.style.display = ''
    } else {
      // 进入全屏
      marsContainer.requestFullscreen()
      if (roadInfoBox) roadInfoBox.style.display = 'none'
      if (polyMainInfoBox) polyMainInfoBox.style.display = 'none'
    }
  }
}

const addWmslayer = (url,layers,id) => {
    let urlstr = resetLayerUrl(url)
    let layer = new mars3d.layer.WmsLayer({
    id: id,
    url: urlstr,
    layers: layers,
    enablePickFeatures:false,
    parameters: {
        transparent: true,
        format: "image/png",
        format_options: "partials:false;group:true",
    },
  });
  window.map.addLayer(layer)
}

const addGeoJson = (url,id) => {
    let urlstr = resetLayerUrl(url)
    let layer = new mars3d.layer.GeoJsonLayer({
    id: id,
    url: urlstr,
    symbol: {
      styleOptions: {
        // opacity: 0.1,
        label: {
          text: "{pile_num}",
          show: true,
          position: "center",
          font_family: "楷体",
          font_size: 24,
          color: id=='glz'?'#ff0000':'#ffffff',
          outline:true,
          outlineColor: '#73b273',
          outlineWidth:10,
          scaleByDistance:true,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0,2500)
        }
      }
    }
  });
  window.map.addLayer(layer)
}


// 修改url
const resetLayerUrl = (url:any) => {
  var arr = []
  var urlstr = ''
  if(url.indexOf('zxchhwy')>0 || url.indexOf('zxchjfj')>0 || url.indexOf('zxchjfn')>0 || url.indexOf('zxchjf')>0){
    return url
  }
  if(url.indexOf('zxch.cpolar.cn') > 0){
    arr = url.split('zxch.cpolar.cn')
    urlstr = '/zxchhwy' + arr[1]
  }
  else if(url.indexOf('139.9.173.189:8090') > 0){
    arr = url.split('139.9.173.189:8090')
    urlstr = '/zxchjfj' + arr[1]
  }
  else if(url.indexOf('139.9.173.189:8091') > 0){
    arr = url.split('139.9.173.189:8091')
    urlstr = '/zxchjfn' + arr[1]
  }
  else if(url.indexOf('139.9.173.189:8080') > 0){
    arr = url.split('139.9.173.189:8080')
    urlstr = '/zxchjf' + arr[1]
  }else{
    ElMessage({
      type: 'warning',
      message: '该资源禁止上传!'
    });
    return false
  }
  return urlstr
}

const changeWms = (id) => {
   const layer = window.map.getLayerById(id);
   if(layer){
    if(id == 'glm'){
      checked1.value = layer.show = !layer.show
    }else if(id == 'glz'){
      checked2.value = layer.show = !layer.show
    }else if(id == 'bmz'){
      checked3.value = layer.show = !layer.show
    }else if(id == 'lczm'){
      checked4.value = layer.show =!layer.show
    }
   }
}
const showMap = () => {
  let base = window.map.getBasemaps()
  base.forEach((element,index) => {
    element.show=index==platType.value?true:false
  });
  mapChecked.value=platType.value*1
  base[base.length-1].show = true
}

const changelayer = (number,type?) => {
  let base = window.map.getBasemaps()
  base.forEach((element,index) => {
    element.show=index==platType.value?true:false
  });
  base[base.length-1].show = true
  base[number].show = true
}

const cancelAddUser = () => {
  dialogTableVisible.value = false
  form.value = {oldPassword:'',password: '',smsCode:''}
}

const reSetPasswordSelf = () => {
  reSetPassWard.value.validate().then(valid=> {
    if(!valid) return
    if(xgFlag.value) {
      resetPwd({oldPassword:form.value.oldPassword,password:form.value.password}).then(res => {
        if(res.code === 200) {
          ElMessage({type: 'success',message: '修改成功!'});
          dialogTableVisible.value = false
          ElMessageBox.alert('登录状态已过期，请重新登录','系统提示',{
            confirmButtonText: '重新登录',
            type: 'warning',
          }).then(() => {
            const useLogin = useMainLogin()
            useLogin.LogOut().then(() => {
              location.href = import.meta.env.VITE_APP_CONTEXT_PATH + "login";
            })
          })
        }
      })
    }else {
      smsResetPwd({smsCode:form.value.smsCode,password:form.value.password}).then(res => {
        if(res.code === 200) {
          ElMessage({type: 'success',message: '修改成功!'});
          dialogTableVisible.value = false
          ElMessageBox.alert('登录状态已过期，请重新登录','系统提示',{
            confirmButtonText: '重新登录',
            type: 'warning',
          }).then(() => {
            const useLogin = useMainLogin()
            useLogin.LogOut().then(() => {
              location.href = import.meta.env.VITE_APP_CONTEXT_PATH + "login";
            })
          })
        }
      })
    }
  })
}

const operatingInstructions = () => {
  user.isFirst = true
  startDrive()
}
</script>

<template>
  <div class="header">
      <div class="lefttitle">

      </div>
      <div class="right">
        <div class="TopBtnBox">
          <POISearch></POISearch>
          <!-- 切换视角 -->
          <span class="TopBtn button" @click="flyTo">
            <img src="@/assets/image/home.png" alt="">
            <span class="tooltip"><div>飞至初始视角</div></span>
          </span>

          <span class="TopBtn button" @click="preview">
            <img src="@/assets/image/yanjing.png" alt="">
            <span class="tooltip"><div>全屏预览</div></span>
          </span>

          <!-- 图层 -->
          <span class="TopBtn">
            <img src="@/assets/image/layer.png" alt="">
            <span class="tooltip">
              <!-- <div class="tooltip_box-header" @click="dialogTableVisible = true">卫星影像</div>
              <div class="tooltip_box-header" @click="user.LogOut()">电子地图</div> -->
              <el-radio-group class="listBox-layer" v-model="mapChecked">
                <el-radio :label="0" @click="changelayer(0)">卫星影像</el-radio>
                <el-radio :label="1" @click="changelayer(1)">电子地图</el-radio>
              </el-radio-group>
            </span>
          </span>

          <!-- 用户 -->
          <span class="TopBtn">
            <img src="@/assets/image/user.png" alt="">
            <span class="tooltip">
              <div class="tooltip_box-header" @click="dialogTableVisible = true">修改密码</div>
              <div class="tooltip_box-header" @click="user.LogOut()">退出登陆</div>
            </span>
          </span>
          

          <span style="margin-right: 50px;"></span>
        </div>
      </div>
  </div>

    <!-- 修改密码 表单 -->
  <el-dialog v-model="dialogTableVisible" >
    <el-form :model="form" :rules="rules" ref="reSetPassWard">
      <div class="xgmmTab">
        <span :class="xgFlag?'select':''">旧密码修改密码</span>
      </div>
        <el-form-item label="旧密码" prop="password">
          <el-input v-model="form.oldPassword" autocomplete="off" type="password" placeholder="首次设置密码无需填写" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="form.password" autocomplete="off" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAddUser">取消</el-button>
          <el-button type="primary" @click="reSetPasswordSelf()">提交</el-button>
        </span>
      </template>
  </el-dialog>
</template>

<style scoped>
.header {
  --header-height: 60px;
  --header-width: calc(100vw - (var(--corner_box_padding) * -2) - 30px);
  --header-width-left: 710px;
  --header-width-middle: calc(var(--header-width) - var(--header-width-left) - var(--header-width-left));
  --header-font-color: #333;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  top: 0;
  width: 100%;
  height: var(--header-height);
  user-select: none;
}
.lefttitle {
  display: flex;
  justify-content: left;
  align-items: start;
  font-size: 22px;
  font-weight: 600;
}
.TopBtnBox {
  display: flex;
  align-items: center;
}
.TopBtnBox .TopBtn {
  box-sizing: border-box;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  cursor: pointer;
  background-color: rgba(29, 30, 34,.8);
  margin-right: 20px;
}
.TopBtnBox .TopBtn img {
  width: 28px;
  height: 28px;
}
.TopBtnBox .TopBtn .iconfont {
  font-size: 24px;
}
.TopBtnBox .TopBtn .iconfont path {
  fill: var(--header-font-color);
}
.TopBtnBox .TopBtn:hover .iconfont {
  animation: bellRing 0.9s both;
}

/* bell ringing animation keyframes*/
@keyframes bellRing {
  0%,
  100% {
    transform-origin: top;
  }

  15% {
    transform: rotateZ(10deg);
  }

  30% {
    transform: rotateZ(-10deg);
  }

  45% {
    transform: rotateZ(5deg);
  }

  60% {
    transform: rotateZ(-5deg);
  }

  75% {
    transform: rotateZ(2deg);
  }
}
.TopBtnBox .TopBtn.button.scale_9 {
  transform: scale(0.9);
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.3);
  color: #fff;
}
.TopBtnBox .TopBtn.button:active {
  transform: scale(0.8);
}

.TopBtnBox .TopBtn.button-bgColor {
  background-color: #3DBDA7;
}

.tooltip {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  font-size: 14px;
  color: var(--header-font-color);
  border-radius: 5px;
  box-shadow: 0 10px 10px rgba(0, 0, 0, 0.1);
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  width: 130px;
  padding: 5px 0;
  background: rgba(255, 255, 255,.2);
  border: 2px solid rgba(255, 255, 255,.5);
  text-align: center;
}

.tooltip::before {
  position: absolute;
  content: "";
  height: 8px;
  width: 8px;
  top: -3px;
  left: 50%;
  transform: translate(-50%) rotate(45deg);
  transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  background: rgba(255, 255, 255, 0.4);
}

.TopBtn:hover .tooltip,
.tooltip:hover {
  top: 50px;
  opacity: 1;
  visibility: visible;
  pointer-events: auto;
}

.TopBtn:hover .tooltip,
.TopBtn:hover .tooltip::before {
  color: var(--header-font-color);
}
.tooltip_box-header:hover {
  background: rgba(0, 0, 0,.4);
  color: #ccc;
}
.path {
    stroke: var(--header-font-color);
}
</style>
<style>
.el-notification {
  background: rgba(0, 0, 0, .8);
}
/* 通知弹窗样式 */
.el-notification__title ,
.el-notification__content ,
.el-notification .el-notification__closeBtn {
  color: #fff;
}

</style>
